﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UITest.Extension;
using Microsoft.VisualStudio.TestTools.UITesting;
using Microsoft.VisualStudio.TestTools.UITesting.WpfControls;

namespace CodedUITestExtensions
{
    /// <summary>
    /// Extensions for WpfCombobox.
    /// </summary>
    public static class WpfComboBoxExtensions
    {
        /// <summary>
        /// Selects combobox item with the expected text, when the text of the control
        /// WpfListItem is not displayed in the property DisplayText.
        /// </summary>
        /// <param name="comboBox">WpfCombobox.</param>
        /// <param name="selectedItemText">Selected combobox item text.</param>
        public static void Select(this WpfComboBox comboBox, string selectedItemText)
        {
            if (comboBox == null)
            {
                throw new ArgumentNullException("comboBox");
            }
            if (selectedItemText == null)
            {
                throw new ArgumentNullException("selectedItemText");
            }
            Mouse.Click(comboBox);
            var listItems = comboBox.Items.Cast<WpfListItem>();
            var itemForSelect = listItems.FirstOrDefault(item => item.GetListItemText().Equals(selectedItemText));
            if (itemForSelect == null)
            {
                throw new UITestControlNotFoundException("Combo box list item with text - " + selectedItemText + " - was not found");
            }
            // Mouse.Click(comboBox) is much faster than using the Expanded property of combobox.
            Mouse.Click(itemForSelect);
        }

        /// <summary>
        /// Returns the text of the selected item of combobox 
        /// when the text is not displayed in the property DisplayText of the control WpfListItem.
        /// </summary>
        /// <param name="comboBox">WpfCombobox.</param>
        /// <returns>Selected combobox item text.</returns>
        public static string GetSelectedListItemText(this WpfComboBox comboBox)
        {
            if (comboBox == null)
            {
                throw new ArgumentNullException("comboBox");
            }
            // Check if the combo box has never expanded, expand and collapse it
            // to define a collection of elements.
            if (comboBox.SelectedIndex == -1)
            {
                Mouse.Click(comboBox);
                Mouse.Click(comboBox);
            }
            List<WpfListItem> listItems = comboBox.Items.Cast<WpfListItem>().ToList();
            return (comboBox.SelectedIndex == -1) 
                ? string.Empty 
                : listItems[comboBox.SelectedIndex].GetListItemText();
        }
    }
}
